﻿/**
 * 查看源码插件
 */
(function(E){
var Consts = E.consts, openHtml = '', Utils = E.mod("Utils");

E.plugin("Source", {
	icon: {
		width: 50,
		text: '源代码',
		
		'default': {
			'Source': {XY:"none" }
		}
	},
	config:{
		width: 800,
		height:400,
		position: 'center',
		overlay: true
	},
	
	// 在插件初始化时执行
	init: function( self ){
		self.cache['html'] = '<textarea name="content" style="width:99%;height:395px;resize:none;"></textarea>';
	},
	
	callback: function( panel, self){
		var html = E.getHTML(false);
		openHtml = formatHtml(html);
		openHtml = openHtml || '<p>\n\n</p>';
		panel.find('textarea[name=content]').val( openHtml );
	},
	
	ok: function(panel, self){
		var Utils = E.mod("Utils"),
			html = panel.find('textarea[name=content]').val(),
			bool = 0;
			
		html = $.trim(html);
		
		// 没有发生改变
		if( html === openHtml ){
			bool = 1;
		}else{
			if( html === '' ){
				html = Consts.IE ? '<p>&nbsp;</p>': '<p><br></p>';
			}else if( !/<\w+/i.test(html) ){
				// 纯文本内容使用p标签包起来
				html = '<p>'+html+'</p>';
			}
			
			E.setHTML(html);
			bool = 1;
			
			/*
			// 暂时取消标签匹配检查 2012-01-13（潘雪鹏）
			var msg = Utils.checkTag(html);
			if( !msg ){
				E.setHTML(html);
				bool = 1;
			}else{
				self.error(msg);
			}
			*/
		}
		return bool;
	}
});


function formatHtml( html ){
	html = html.replace(/\n+/g, '');
	
	var wrap = $('<div></div>').append( html ),
		itemHtml='',
		child = null;
		
	wrap.children().each(function(i, el){
		// jquery-1.4.2 IE下会出现异常
		try{
			child = $(this);
			itemHtml = child.html();
			if(itemHtml.length > 50){
				child.html('\n'+itemHtml+'\n');
			}
			child.after('\n');
		}catch(e){}
	});
	
	var table = wrap.find("table");
	if( table.size() ){
		table.find("tr,td,th").after('\n').before('\n');
	}
	
	html = wrap.html();
	html = html.replace(/\n+/g, '\n');
	html = html.replace(/<BR>/ig, '<br>\n');
	
	html = html.replace(/<.+?>/ig, function($0){
		$0 = $0.replace(/COLOR:/g, 'color:');
		$0 = $0.replace(/rgb\(\d+,(?: |&nbsp;)?\d+,(?: |&nbsp;)?\d+\)/ig, function($0){
			return Utils.colorToHex($0);
		});
		return $0;
	});
	
	// IE下将标签转为小写
	if( Consts.IE ){
		html = html.replace(/<(\w+)/ig, function($0, tagName){
			return '<'+tagName.toLowerCase();
		});
		html = html.replace(/(\w+)>/ig, function($0, tagName){
			return tagName.toLowerCase()+'>';
		});
	}
	
	return html;
}

/*
function formatHtml( html ){
	html = html.replace(/<p([^>]*)>/ig, '\n<p$1>\n')
		.replace(/<\/p>/ig, '\n</p>\n')
		.replace(/<br \/>/ig, '<br />\n')
		.replace(/\s\n<\/p>/ig, '\n</p>')
		.replace(/<p([^>]*)>\n+/ig, '<p$1>\n')
		.replace(/<p(?:[^>]*)>\s*<\/p>/ig, '')
		.replace(/\n{2,}/ig, '\n');
		
	return $.trim(html);
}
*/
})(jQEditor);